package com.genesis.yunnanji.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.genesis.yunnanji.Constants;
import com.genesis.yunnanji.bean.WXAccessTokenBean;
import com.genesis.yunnanji.bean.WXUserInfoBean;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.youth.xframe.utils.http.HttpCallBack;
import com.youth.xframe.utils.http.XHttp;
import com.youth.xframe.utils.log.XLog;
import com.youth.xframe.widget.XToast;

import org.greenrobot.eventbus.EventBus;

import java.util.LinkedHashMap;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;

    private static final int RETURN_MSG_TYPE_LOGIN = 1; //登录
    private static final int RETURN_MSG_TYPE_SHARE = 2; //分享

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, Constants.WEIXIN_APPID, false);
        // 将该app注册到微信
        api.registerApp(Constants.WEIXIN_APPID);

        // 注意：第三方开发者如果使用透明界面来实现WXEntryActivity，需要判断handleIntent的返回值，
        // 如果返回值为false，则说明入参不合法未被SDK处理，应finish当前透明界面，避免外部通过传递非法参数的Intent导致停留在透明界面，引起用户的疑惑
        try {
            api.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                break;
            default:
                break;
        }
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        XLog.e("BaseResp:" + JSON.toJSONString(resp));
        int type = resp.getType(); //类型：分享还是登录
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (resp instanceof SendAuth.Resp) {
                    SendAuth.Resp newResp = (SendAuth.Resp) resp;
                    XLog.e("SendAuth.Resp:" + JSON.toJSONString(newResp));
                    //获取微信传回的code
                    String code = newResp.code;

                    XLog.e("Weixin Code:" + code);
//                    RxBus.get().post(Constants.HTTP_LOGIN_WEIXIN, code);
                }
                //用户同意
                if (type == RETURN_MSG_TYPE_LOGIN) {
                    //用户换取access_token的code，仅在ErrCode为0时有效
                    String code = ((SendAuth.Resp) resp).code;
                    //这里拿到了这个code，去做2次网络请求获取access_token和用户个人信息
//                    WXLoginUtils().getWXLoginResult(code, this);
                    getWXAccess_token(code);
                } else if (type == RETURN_MSG_TYPE_SHARE) {
                    XToast.success("微信分享成功");
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                String message = "";
                if (type == RETURN_MSG_TYPE_LOGIN) {
                    message = "取消了微信登录";
                } else if (type == RETURN_MSG_TYPE_SHARE) {
                    message = "取消了微信分享";
                }
                XToast.info(message);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                XToast.error("拒绝授权微信登录");
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                break;
            default:
                break;
        }
        finish();
    }

    private void getWXAccess_token(String code) {
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("appid", Constants.WEIXIN_APPID);
        params.put("secret", Constants.WEIXIN_APPSECRET);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        XHttp.obtain().get(Constants.WXACCESS_TOKEN, params, new HttpCallBack<WXAccessTokenBean>() {
            @Override
            public void onSuccess(WXAccessTokenBean bean) {
                String access_token = bean.getAccess_token();
                String openid = bean.getOpenid();
                getWXUserInfo(access_token, openid);
            }

            @Override
            public void onFailed(String error) {

            }
        });
    }

    private void getWXUserInfo(String access_token, String openid) {
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("access_token", access_token);
        params.put("openid", openid);
        XHttp.obtain().get(Constants.WXUSER_INFO, params, new HttpCallBack<WXUserInfoBean>() {
            @Override
            public void onSuccess(WXUserInfoBean bean) {
                XLog.e(bean.getNickname());
                String openid1 = bean.getOpenid();
                String nickname = bean.getNickname();
                int sex = bean.getSex();
                String headimgurl = bean.getHeadimgurl();
                EventBus.getDefault().post(bean);
            }

            @Override
            public void onFailed(String error) {

            }
        });
    }
}